package cn.sylinx.hbatis.ext.ctxds;

import java.util.Iterator;
import java.util.ServiceLoader;
import java.util.concurrent.locks.ReentrantLock;

class SPIManager {

	private static DynamicDatasourceProvider dynamicDatasourceProvider;

	private static ReentrantLock lock = new ReentrantLock();

	static DynamicDatasourceProvider getDynamicDatasourceProvider() {

		if (dynamicDatasourceProvider != null) {
			return dynamicDatasourceProvider;
		}

		// 加載DynamicDatasourceProvider
		loadDynamicDatasourceProvider();

		return dynamicDatasourceProvider;

	}

	private static void loadDynamicDatasourceProvider() {

		try {

			lock.lock();

			if (dynamicDatasourceProvider == null) {

				ServiceLoader<DynamicDatasourceProvider> sl = ServiceLoader.load(DynamicDatasourceProvider.class);
				Iterator<DynamicDatasourceProvider> it = sl.iterator();
				dynamicDatasourceProvider = it.hasNext() ? it.next() : null;
			}

			if (dynamicDatasourceProvider == null) {
				dynamicDatasourceProvider = new DefaultDynamicDatasourceProvider();
			}

		} finally {
			lock.unlock();
		}

	}

}
